package com.primaryedu.ui.app.growstep;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.bean.GradelistBean;
import com.primaryedu.data.Contants;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.ui.app.parentsch.VoteDetailsActivity;
import com.primaryedu.widget.PullToRefreshView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 班级列表
 *
 * @author jun.wang
 * @description
 * @data 2018年1月9日
 */
public class GradeListActivity extends BaseActivity implements OnClickListener, PullToRefreshView.OnFooterRefreshListener, PullToRefreshView.OnHeaderRefreshListener {
    private ListView listView;
    GradeListAdapter adapter;
    private int page = 1;
    private PullToRefreshView pullToRefreshView;
    private boolean fistenter = true;
    private ArrayList<GradelistBean.DataBean.ListBean> gradeLists = new ArrayList<>();
    private List<GradelistBean.DataBean.ListBean> gradetempList = new ArrayList<>();
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
                    if (null != gradetempList && gradetempList.size() != 0) {
                        adapter = new GradeListAdapter(GradeListActivity.this, gradetempList);
                        listView.setAdapter(adapter);
                    }
                    break;
                case 1002:
                    if (gradetempList != null && gradetempList.size() != 0) {
                        adapter.updateGradeView(gradetempList);
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_grade_list);

        init();
        getgradeList(true);
    }

    private void getgradeList(boolean fistenter) {
        if (fistenter) {
            showLoading("加载中...");
        }
        page = 1;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.gradeList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response=masterboxlist=======" + response);
                        page++;
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");

                                gradeLists = new Gson().fromJson(listStr,
                                        new TypeToken<List<GradelistBean.DataBean.ListBean>>() {
                                        }.getType());
                                gradetempList.clear();
                                gradetempList.addAll(gradeLists);
                                handler.sendEmptyMessage(1001);
////								}

                                System.out.println("leaveLists==" + listStr);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("访问失败，请重新刷新下拉刷新！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
//				map.put("status", "1");
                map.put("pageSize", "50");
                map.put("pageNo", page + "");
                return map;

            }
        };
        requestQueue.add(stringRequest);
    }

    private void init() {
        ((TextView) findViewById(R.id.title)).setText("班级信息");
        findViewById(R.id.back).setOnClickListener(this);
        listView = (ListView) this.findViewById(R.id.listView);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                GradelistBean.DataBean.ListBean vb = gradetempList.get(position);
//                Intent intent = new Intent(GradeListActivity.this, ClassDynamicActiviy.class);
                Intent intent = new Intent();
                intent.putExtra("className", vb.getClassName());
                intent.putExtra("calssId", vb.getId());
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        pullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
        pullToRefreshView.setOnHeaderRefreshListener(this);
        pullToRefreshView.setOnFooterRefreshListener(this);
        pullToRefreshView.setLastUpdated(new Date().toLocaleString());
    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_grade_list;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.back:
                finish();
                break;

            default:
                break;
        }

    }

    private void requestmoregradeList() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.gradeList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("response=masterboxlist=======" + response);
                        page++;
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {

                                String data = json.getString("data");
                                if (data.contains("list")) {
                                    JSONObject listObj = new JSONObject(data);
                                    String listStr = listObj.getString("list");

                                    gradeLists = new Gson().fromJson(listStr,
                                            new TypeToken<List<GradelistBean.DataBean.ListBean>>() {
                                            }.getType());
//
                                    gradetempList.addAll(gradeLists);
                                    handler.sendEmptyMessage(1002);
                                } else {
                                    showToast("已经加载完全部数据！");
                                }
//								System.out.println("leaveLists=="+listStr);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                return map;

            }
        };
        requestQueue.add(stringRequest);
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
//				uploadMore = true;

                requestmoregradeList();
                pullToRefreshView.onFooterRefreshComplete();

            }

        }, 1500);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {
            @Override
            public void run() {
                getgradeList(false);
                pullToRefreshView.onHeaderRefreshComplete("更新于:"
                        + Calendar.getInstance().getTime().toLocaleString());
                pullToRefreshView.onHeaderRefreshComplete();
                Toast.makeText(GradeListActivity.this, "数据刷新完成!", Toast.LENGTH_LONG).show();
            }

        }, 1500);
    }
}
